#include <QApplication>
#include <QMessageBox>
#include "logindialog.h"
#include "client_network.h"
#include "request_sender.h"
#include "registerdialog.h"
#include "chatwindow.h"

int main(int argc, char *argv[])
{
    //连接到服务器
    // ClientNetwork client;
    // client.connectToServer("127.0.0.1",12345);

    QApplication a(argc, argv);

    ClientNetwork clientNet;
    clientNet.connectToServer("127.0.0.1", 12345);
    RequestSender request(&clientNet);

    // 预创建所有窗口但不显示
    LoginDialog login(&request,&clientNet);
    RegisterDialog *registerDialog = new RegisterDialog(&clientNet);
    registerDialog->setAttribute(Qt::WA_DeleteOnClose);
    ChatWindow *chatWindow = new ChatWindow(&clientNet);
    chatWindow->setAttribute(Qt::WA_DeleteOnClose);

    // 连接登录界面的注册按钮信号
    QObject::connect(&login, &LoginDialog::requestShowRegister, [&](){
        login.hide();
        registerDialog->show();
    });

    // 连接注册界面的返回按钮信号
    QObject::connect(registerDialog, &RegisterDialog::backToLoginRequested, [&](){
        registerDialog->hide();
        login.show();
    });

    // 连接登录成功信号 - 跳转到聊天窗口
    QObject::connect(&login, &LoginDialog::loginSuccess, [&](const QString &username){
        login.hide();
        chatWindow->username=username;
        chatWindow->setWindowTitle(QString("Qt聊天室 - 当前用户: %1").arg(username));
        chatWindow->show();
    });

    QObject::connect(registerDialog, &RegisterDialog::registerSuccess, [&]() {
        registerDialog->hide();  // 关闭注册窗口
        login.show();     // 显示登录窗口
    });

    // 连接聊天窗口的退出信号 - 返回登录界面
    QObject::connect(chatWindow, &ChatWindow::logoutRequested, [&](){
        chatWindow->hide();
        login.clearFields();
        login.show();
    });

    // 显示登录窗口
    login.show();

    return a.exec();
}
